<?php

if(!defined("IN_PHPSCUP"))exit("hacking");
/**
*读文件函数
**/
function read_file($filename,$method="rb")
{
	if($handle=@fopen($filename,$method))
	{
		@flock($handle,LOCK_SH);
		$filedata=@fread($handle,@filesize($filename));
		@fclose($handle);
	}
	return $filedata;
}

/**
*写文件函数
**/
function write_file($filename,$data,$method="rb+",$iflock=1)
{
	@touch($filename);
	$handle=@fopen($filename,$method);
	if($iflock)
	{
		@flock($handle,LOCK_EX);
	}
	@fputs($handle,$data);
	
	if($method=="rb+")
	{
	    @ftruncate($handle,strlen($data));
	}
	
	@fclose($handle);
	@chmod($filename,0777);	
	if( is_writable($filename) )
	{
		return 1;
	}else
	{
		return 0;
	}
}

/**
*删除文件,值不为空，则返回不能删除的文件名
**/
function del_file($path)
{
    $show ="";
	if (file_exists($path))
	{
		if(is_file($path))
		{
			if(	!@unlink($path)	)
			{
				$show.="$path,";
			}
		} 
		else
		{
			$handle = opendir($path);
			while (($file = readdir($handle))!='') 
			{
				if (($file!=".") && ($file!="..") && ($file!=""))
				{
					if (is_dir("$path/$file"))
					{
						$show.=del_file("$path/$file");
					} 
					else
					{
						if( !@unlink("$path/$file") )
						{
							$show.="$path/$file,";
						}
					}
				}
			}
			closedir($handle);
			if(!@rmdir($path))
			{
				$show.="$path,";
			}
		}
	}
	return $show;
}

/*
将数组中值为空的的值去除
*/
function del_empty_var($array){
    
	 foreach($array as $key => $value)
	 {
	     if(empty($value))
	     {
	      unset($array[$key]);
	     }
	 
	 }
	
	return $array;
}

/*
将数组中值为空的的值去除
*/
function del_empty_var_1($array){
	
	$tmp_array=array();
    
	 foreach($array as $key => $value)
	 {
	     if(strlen($value)>=2)
	     {
	     	$key =substr($value, 0,2);
	     	$tmp_array[$key]=$value;
	     }
	 }
	
	return $tmp_array;
}


//多维数组按$k值排序$arr多维数组 
function array_var_sort(&$arr,$k)
{   
	  if(empty($k))return false;
	  $list=array();	  
      foreach ($arr as $key => $value) 
	  { 

         $list[$key] = $value[$k]; 
      } 
	  if(!is_array($list))return false;	  
      array_multisort($list, $arr);

}





if(!function_exists('json_encode')) 
{
	function json_encode($arg) 
	{
		$returnValue = '';
		$c           = '';
		$i           = '';
		$l           = '';
		$s           = '';
		$v           = '';
		$numeric     = true;

		switch (gettype($arg))
		 {
			case 'array':
				foreach ($arg AS $i => $v) 
				{
					if (!is_numeric($i)) 
					{
						$numeric = false;
						break;
					}
				}

				if ($numeric) 
				{
					foreach ($arg AS $i => $v) 
					{
						if (strlen($s) > 0) 
						{
							$s .= ',';
						}
						$s .= json_encode($arg[$i]);
					}

					$returnValue = '[' . $s . ']';
				} 
				else 
				{
					foreach ($arg AS $i => $v) 
					{
						if (strlen($s) > 0) 
						{
							$s .= ',';
						}
						$s .= json_encode($i) . ':' . json_encode($arg[$i]);
					}

					$returnValue = '{' . $s . '}';
				}
				break;

			case 'object':
				foreach (get_object_vars($arg) AS $i => $v) 
				{
					$v = json_encode($v);

					if (strlen($s) > 0) 
					{
						$s .= ',';
					}
					$s .= json_encode($i) . ':' . $v;
				}

				$returnValue = '{' . $s . '}';
				break;

			case 'integer':
			case 'double':
				$returnValue = is_numeric($arg) ? (string) $arg : 'null';
				break;

			case 'string':
				$returnValue = '"' . strtr($arg, array(
					"\r"   => '\\r',    "\n"   => '\\n',    "\t"   => '\\t',     "\b"   => '\\b',
					"\f"   => '\\f',    '\\'   => '\\\\',   '"'    => '\"',
					"\x00" => '\u0000', "\x01" => '\u0001', "\x02" => '\u0002', "\x03" => '\u0003',
					"\x04" => '\u0004', "\x05" => '\u0005', "\x06" => '\u0006', "\x07" => '\u0007',
					"\x08" => '\b',     "\x0b" => '\u000b', "\x0c" => '\f',     "\x0e" => '\u000e',
					"\x0f" => '\u000f', "\x10" => '\u0010', "\x11" => '\u0011', "\x12" => '\u0012',
					"\x13" => '\u0013', "\x14" => '\u0014', "\x15" => '\u0015', "\x16" => '\u0016',
					"\x17" => '\u0017', "\x18" => '\u0018', "\x19" => '\u0019', "\x1a" => '\u001a',
					"\x1b" => '\u001b', "\x1c" => '\u001c', "\x1d" => '\u001d', "\x1e" => '\u001e',
					"\x1f" => '\u001f'
				)) . '"';
				break;

			case 'boolean':
				$returnValue = $arg?'true':'false';
				break;

			default:
				$returnValue = 'null';
		}

		return $returnValue;
	}
}






/**
 * 如果系统不存在file_put_contents函数则声明该函数
 *
 * @author  wj
 * @param   string  $file
 * @param   mix     $data
 * @return  int
 */
if (!function_exists('file_put_contents'))
{
    if (!defined('LOCK_EX'))
    {
        define('LOCK_EX', 'LOCK_EX');
    }
    function file_put_contents($file, $data, $mode = '')
    {
        $contents = (is_array($data)) ? implode('', $data) : $data;

        $mode = (empty($mode)) ? 'ab+' : 'wb';

        if (($fp = @fopen($file, $mode)) === false)
        {
            return false;
        }
        else
        {
            $bytes = fwrite($fp, $contents);
            fclose($fp);

            return $bytes;
        }
    }
}


/**
*生成目录
**/
function get_dir($path){
	//这个\没考虑
			$newpath="";
    $path =str_replace("\\","/",$path);
	$ROOT_PATH =str_replace("\\","/",ROOT_PATH);
	$detail=explode("/",$path);
	foreach($detail AS $key=>$value){
		if($value==''&&$key!=0){
			//continue;
		}
		$newpath.="$value/";
		if((preg_match("/^\//i",$newpath)||preg_match("/:/i",$newpath))&&!strstr($newpath,$ROOT_PATH)){continue;}
		if( !is_dir($newpath) ){
			if(substr($newpath,-1)=='\\'||substr($newpath,-1)=='/')
			{
				$_newpath=substr($newpath,0,-1);
			}
			else
			{
				$_newpath=$newpath;
			}
			if(!is_dir($_newpath)&&!mkdir($_newpath)&&ereg("^\/",$ROOT_PATH)){
				return 'false';
			}
			@chmod($newpath,0777);
		}
	}
	return $path;
}



function random($length){ 
	$seed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; 
	$str = "";
	while(strlen($str) < $length){ 
		  $str .= substr($seed,(mt_rand() % strlen($seed)),1); 
	} 
	return $str; 
} 



/**
 * 获得用户的真实IP地址
 *
 * @return  string
 */
function get_ip()
{
    static $realip = NULL;

    if ($realip !== NULL)
    {
        return $realip;
    }

    if (isset($_SERVER))
    {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

            /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
            foreach ($arr AS $ip)
            {
                $ip = trim($ip);

                if ($ip != 'unknown')
                {
                    $realip = $ip;

                    break;
                }
            }
        }
        elseif (isset($_SERVER['HTTP_CLIENT_IP']))
        {
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        }
        else
        {
            if (isset($_SERVER['REMOTE_ADDR']))
            {
                $realip = $_SERVER['REMOTE_ADDR'];
            }
            else
            {
                $realip = '0.0.0.0';
            }
        }
    }
    else
    {
        if (getenv('HTTP_X_FORWARDED_FOR'))
        {
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        }
        elseif (getenv('HTTP_CLIENT_IP'))
        {
            $realip = getenv('HTTP_CLIENT_IP');
        }
        else
        {
            $realip = getenv('REMOTE_ADDR');
        }
    }

    preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
    $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';

    return $realip;
}
function check_rand($lenth)
{
         $chars = "abcdefghikmnprstuvwxy3456789";
         $string = "";
         for ($i = 0; $i < $lenth; $i++) 
		 {
		 $string .= $chars[rand(0, strlen($chars) - 1)];
		 }
         return $string;
}
function filtrate($msg){

		$msg = str_replace('"','&quot;',$msg);
		$msg = str_replace("'",'&#39;',$msg);
/*		$msg = str_replace("<","&lt;",$msg);
		$msg = str_replace(">","&gt;",$msg);*/
		$msg = str_replace("\t","   &nbsp;  &nbsp;",$msg);
		$msg = str_replace("   "," &nbsp; ",$msg);
		return $msg;
}
/**
* 字符截取
* @param string $string 要截取的字符串
* @param int $length 要截取的字符串长度
* @param string $dot 省略号
**/
function psp_cutstr($string, $length=20, $dot = '...') 
{
	if($length < 1 || ($len = strlen($string)) <= $length) return $string;
	
	$string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);

	$_string = '';
	if(strtolower(VIEW_CHARSET) == 'utf-8') 
	{

		$n = $tn = $noc = 0;
		while($n < $len) 
		{

			$t = ord($string[$n]);
			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126))
			{
				$tn = 1; $n++; $noc++;
			}elseif(194 <= $t && $t <= 223)
			{
				$tn = 2; $n += 2; $noc += 2;
			}elseif(224 <= $t && $t <= 239)
			{
				$tn = 3; $n += 3; $noc += 2;
			}elseif(240 <= $t && $t <= 247)
			{
				$tn = 4; $n += 4; $noc += 2;
			}elseif(248 <= $t && $t <= 251)
			{
				$tn = 5; $n += 5; $noc += 2;
			}elseif($t == 252 || $t == 253)
			{
				$tn = 6; $n += 6; $noc += 2;
			}else
			{
				$n++;
			}

			if($noc >= $length) 
			{
				break;
			}
		}
		if($noc > $length) 
		{
			$n -= $tn;
		}
		$_string = substr($string, 0, $n);
	} else 
	{
		
		for($i = 0; $i < $length; $i++) 
		{
			if(!isset($string[$i])) break;
			
			$_string .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
		}
	}

	$_string = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $_string);

	return $_string.$dot;
}



?>